import {createBrowserHistory} from "plain-history";
import {reactive, RenderNode} from "@peryl/react-compose";
import {Page404} from "./routers/404";
import {PlainLogo} from "@peryl/icon/src/packages/component/logo/react";
import React from "react";

export const AppRouter = (() => {
  const history = createBrowserHistory({ base: '/react-cms-visual-editor' });

  const state = reactive({
    route: history.state.route,
    renderPage: null as null | (() => RenderNode),
    loading: true,
  });

  history.onPathChange((route) => {
    state.route = route;
    loadPage();
  });

  const loadPage = async () => {
    state.loading = true;
    let initPath = history.state.route.path;
    console.log('-->> app:', { initPath });
    if (!initPath || initPath === '/') {
      initPath = '/basic';
    }
    try {
      const _module = await import('src/pages/routers' + initPath + '.tsx');
      state.renderPage = () => <_module.default/>;
    } catch (e) {
      console.error(e);
      state.renderPage = null;
    } finally {
      state.loading = false;
    }
  };

  const render = () => {
    if (state.loading) {
      return <div style={{ height: '100px', textAlign: 'center', lineHeight: '100px' }}><PlainLogo loading/></div>;
    }
    if (!!state.renderPage) {
      return state.renderPage();
    } else {
      return <Page404/>;
    }
  };

  loadPage();

  return {
    render,
    history,
    state,
  };
})();
